<template>
  <PageWrapper :title="orderInfoData?.projectName + '--' + orderInfoData?.csubProject.subProjectName" contentBackground>
    <template #extra>
      <div v-if="orderInfoData?.csubProject.status === '报价中' && orderInfoData?.csubProject.userId === orderInfoData?.sysUser.id">
        <a-button v-auth="'project:c_sub_project:quote'" type="primary" @click="quoteAdd">提交报价</a-button>
      </div>
      <div v-if="orderInfoData?.csubProject.status === '审核中'">
        <a-button v-auth="'project:c_sub_project:quotationReview'">审核中</a-button>
      </div>
      <div v-if="orderInfoData?.csubProject.userId === orderInfoData?.sysUser.id">
        <a-button v-auth="'project:c_sub_project:uploadcontract'" type="dashed" @click="uploadContract">上传合同</a-button>
      </div>
      <div v-if="orderInfoData?.csubProject.status === '报价完成'">
        <a-button v-auth="'project:c_sub_project:quotationReview'" type="primary" @click="updateStatus('开始施工')">开始施工</a-button>
        <a-button v-auth="'project:c_sub_project:quotationReview'" type="dashed" @click="updateStatus('重新报价')">重新报价</a-button>
        <a-button v-auth="'project:c_sub_project:quotationReview'" type="primary" @click="updateStatus('关闭')">关闭</a-button>
      </div>
      <div v-if="orderInfoData?.csubProject.status === '施工中'">
        <a-button v-auth="'project:c_sub_project:quotationReview'" type="primary" @click="updateStatus('完成')">完成</a-button>
      </div>
    </template>

    <div class="pt-4 m-4 desc-wrap">
      <a-descriptions size="small" :column="2">
        <a-descriptions-item label="项目名称">{{ orderInfoData?.csubProject.subProjectName }}</a-descriptions-item>
        <a-descriptions-item label="项目描述">{{ orderInfoData?.csubProject.subProjectDescription }}</a-descriptions-item>
        <a-descriptions-item label="最新报价">{{ orderInfoData?.csubProject.totalQuotation }}(含税)</a-descriptions-item>
        <a-descriptions-item label="项目状态">{{ orderInfoData?.csubProject.status }}</a-descriptions-item>
        <a-descriptions-item label="地址">{{ orderInfoData?.csubProject.address }}</a-descriptions-item>
        <a-descriptions-item label="项目预算">{{ orderInfoData?.csubProject.budget }}(含税)</a-descriptions-item>
        <a-descriptions-item label="合同文件">
          <a href="#" v-if="orderInfoData?.csubProject.fileRecordId != null && orderInfoData?.csubProject.fileRecordId != ''"
             @click="handleViewFile(orderInfoData?.csubProject.fileRecordId)">
            查看
          </a><span v-else>无文件</span>

        </a-descriptions-item>

        <a-descriptions-item label="附件">
           <a
            href="#"
            v-if="orderInfoData?.csubProject.attachmentUrl != null && orderInfoData?.csubProject.attachmentUrl != ''"
            @click="handleViewFile(orderInfoData?.csubProject.attachmentUrl)"
          >
            查看</a>
          <span v-else>无文件</span>
        </a-descriptions-item>
      </a-descriptions>

      <a-card title="流程进度" :bordered="false">
        <a-steps :current="currentStep" progress-dot size="small">
          <a-step
            v-for="(item, index) in allSteps"
            @click="updateStatue(orderInfoData?.csubProject.id, item.newStatus)"
            :key="index"
            :title="item.newStatus"
          >
            <template #description>
              <p>{{ item.changeTime }}</p>
              <div>{{ item.remark }}</div>
            </template>
          </a-step>
        </a-steps>
      </a-card>

      <a-card title="分包商信息" :bordered="false" class="mt-5">
        <a-descriptions :column="3">
          <a-descriptions-item label="分包商">{{ orderInfoData?.ccontractorInfo.contactName }}</a-descriptions-item>
          <a-descriptions-item label="权限用户">{{ orderInfoData?.ccontractorInfo.userName }}</a-descriptions-item>
          <a-descriptions-item label="联系人">{{ orderInfoData?.ccontractorInfo.contactPerson }}</a-descriptions-item>
          <a-descriptions-item label="联系电话">{{ orderInfoData?.ccontractorInfo.contactPhone }}</a-descriptions-item>
          <a-descriptions-item label="地址">{{ orderInfoData?.ccontractorInfo.address }} </a-descriptions-item>
          <a-descriptions-item label="电子邮箱">{{ orderInfoData?.ccontractorInfo.email }} </a-descriptions-item>
          <a-descriptions-item label="合作模式">{{ orderInfoData?.ccontractorInfo.conspireMode }} </a-descriptions-item>
          <a-descriptions-item label="分包商类型">{{ orderInfoData?.ccontractorInfo.contactType }} </a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-tabs v-model:activeKey="activeTabKey">
        <a-tab-pane key="quoteRecord" :force-render="true" tab="报价">
          <CProjectQuoteListInfoModal ref="projectQuoteRef" :csubProjectId="orderInfoData?.csubProject.id"> </CProjectQuoteListInfoModal>
        </a-tab-pane>
        <a-tab-pane key="payment" :force-render="true" tab="付款记录">
          <PaymentRequestModal   ref="paymentRequestRef" :csubProjectId="orderInfoData?.csubProject.id"> </PaymentRequestModal>
        </a-tab-pane>
        <a-tab-pane key="acceptance" :force-render="true" tab="验收记录">
          <AcceptanceRecordModal ref="acceptanceRef" :projectId="orderInfoData?.projectId" :csubProjectId="orderInfoData?.csubProject.id"> </AcceptanceRecordModal>
        </a-tab-pane>

        <a-tab-pane key="contract" :force-render="true" tab="合同记录">
          <ContractInfoModal ref="contractRef" :projectId="orderInfoData?.projectId" :csubProjectId="orderInfoData?.csubProject.id"> </ContractInfoModal>
        </a-tab-pane>
        <a-tab-pane key="fileRecord" :force-render="true" tab="相关文件">
          <fileRecordModal  ref="fileRef" :projectId="orderInfoData?.projectId" :csubProjectId="orderInfoData?.csubProject.id"> </fileRecordModal>
        </a-tab-pane>
      </a-tabs>
    </div>
  </PageWrapper>
  <CProjectQuoteModal ref="registerModal" @success="handleSuccess"></CProjectQuoteModal>
  <CContractModal ref="ContractregisterModal" @success="handleSuccess"></CContractModal>
  <!-- 引入 ViewFileDetail 组件 -->
  <ViewFileDetail ref="viewFileDetailRef" @view-file="viewFileDetail = $event"></ViewFileDetail>

  <!-- 修改状态 -->
  <CSubProjectStatusLogModal ref="subProjectStatusLogRegisterModal" @success="handleSuccess"></CSubProjectStatusLogModal>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, reactive } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Divider, Card, Empty, Descriptions, Steps, Tabs, Select } from 'ant-design-vue';
  import { getOrderInfo, postUpdateStatus } from './orderInfo.api';
  import { useRoute } from 'vue-router';
  import PaymentRequestModal from '../paymentrequest/CPaymentRequestListInfo.vue';
  import CProjectQuoteListInfoModal from '../projectquote/CProjectQuoteListInfo.vue';
  import AcceptanceRecordModal from '../acceptancerecord/CAcceptanceRecordListInfo.vue';
  import CProjectQuoteModal from '../projectquote/components/CProjectQuoteModal.vue';
  import ContractInfoModal from '../contrac/CContractListInfo.vue';
  import fileRecordModal from '../filerecord/CFileRecordListInfo.vue';
  import CContractModal from '../contrac/components/CContractModal.vue';
  import ViewFileDetail from '@/components/FileView/ViewFileDetail.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import CSubProjectStatusLogModal from '../subprojectstatuslog/components/CSubProjectStatusLogModal.vue';
  import jeecg from '@/views/demo/jeecg/index.vue';
  import { useTabs } from "@/hooks/web/useTabs";
  const { createMessage } = useMessage();
  const registerModal = ref();
  const ContractregisterModal = ref();
  const subProjectStatusLogRegisterModal = ref();

  const projectQuoteRef   = ref()
  const paymentRequestRef  = ref()
  const acceptanceRef  = ref()
  const contractRef  = ref()
  const fileRef  = ref()

  const { isAuth } = usePermission();
  // 从子组件获取 viewFileDetail 方法
  const viewFileDetail = ref();
  const viewFileDetailRef = ref();
  // 在 table 的插槽中使用 viewFileDetail 方法
  function handleViewFile(url) {
    debugger
    viewFileDetail.value(url);
  }

  const activeTabKey = ref('quoteRecord');
  export default defineComponent({
    components: {
      ViewFileDetail,
      CContractModal,
      CSubProjectStatusLogModal,
      BasicTable,
      CProjectQuoteListInfoModal,
      PaymentRequestModal,
      ContractInfoModal,
      AcceptanceRecordModal,
      CProjectQuoteModal,
      fileRecordModal,
      PageWrapper,
      [Divider.name]: Divider,
      [Card.name]: Card,
      Empty,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      [Steps.name]: Steps,
      [Steps.Step.name]: Steps.Step,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const projectId = ref<string | null>(null);
      const subProjectId = ref<string | null>(null);
      const subProjectStatusLogs = ref<any[]>([]);
      const currentStep = ref<number>(0);
      // 承包商下拉框选项
      let contractorOptions = ref();
      // 使用 useRoute 获取当前路由信息
      const route = useRoute();
      const orderInfoData = ref();
      const quot = ref();
      const contractorId = ref();
      // 定义所有可能的步骤
      const allSteps = reactive([
        { newStatus: '报价中', remark: '', changeTime: '', num: 0 },
        { newStatus: '审核中', remark: '', changeTime: '', num: 1 },
        { newStatus: '报价完成', remark: '', changeTime: '', num: 2 },
        { newStatus: '驳回', remark: '', changeTime: '', num: 3 },
        { newStatus: '施工中', remark: '', changeTime: '', num: 4 },
        { newStatus: '施工完成', remark: '', changeTime: '', num: 5 },
        { newStatus: '待验收', remark: '', changeTime: '', num: 6 },
        { newStatus: '验收完成', remark: '', changeTime: '', num: 7 },
        { newStatus: '质保阶段', remark: '', changeTime: '', num: 8 },
        { newStatus: '质保完成', remark: '', changeTime: '', num: 9 },
      ]);
      // 自定义筛选逻辑
      const filterOption = (input: string, option: any) => {
        return option.label.toLowerCase().includes(input.toLowerCase());
      };


      async function orderInfo() {
        try {
          const params = { id: projectId.value, subProjectId: subProjectId.value };
          const result = await getOrderInfo(params);
          subProjectId.value;
          orderInfoData.value = result;
          quot.value = result.quot;

          contractorId.value = result.contractorId;

          // 动态设置流程进度数据
          subProjectStatusLogs.value = result.subProjectStatusLogs || [];
          //
          const data = subProjectStatusLogs.value[0];
          let statusFlag = true;
          // 根据返回的流程进度日志更新描述和时间
          let num = 0;
          allSteps.forEach((step, index) => {
            const log = subProjectStatusLogs.value.find((log) => log.newStatus === step.newStatus);
            if (log && statusFlag) {
              step.remark = log.remark || '';
              step.changeTime = log.changeTime || '';
              currentStep.value = step.num;
              if (data.newStatus === log.newStatus) {
                //后面的状态就不处理了
                statusFlag = false;
              }
            } else {
              step.remark = '';
              step.changeTime = '';
            }
          });
        } catch (error) {}
      }

      // 在页面加载时调用 getOrderInfo 方法
      /*      onMounted(() => {
        projectId.value = route.query.projectId as string;
        subProjectId.value = route.query.subProjectId as string;
        subProjectId;
        orderInfo();
        quote();
      });*/

      const { setTitleByPath } = useTabs();
      onMounted(async () => {
        projectId.value = route.query.projectId as string;
        subProjectId.value = route.query.subProjectId as string;
        subProjectId;
        // 确保 orderInfo 和 quote 按顺序执行
        await orderInfo();
        await quote();
        await quotationReview();


         //设置tab名称
          const title = orderInfoData.value?.csubProject.subProjectName? `子项目 - ${orderInfoData.value?.csubProject.subProjectName}`
            : '子项目详情';
            setTitleByPath(title,route.fullPath);
      });

      /**
       * 报价新增
       */
      function quoteAdd() {
        const defaultValueRef = reactive<Record<string, any>>({
          projectId: projectId.value,
          subProjectId: subProjectId.value,
        });
        registerModal.value.disableSubmit = false;
        registerModal.value.add(defaultValueRef);
      }

      /**
       * 报价审核
       */
      function quoteEdit() {
        if (quot != null && quot.value != null) {
          registerModal.value.disableSubmit = false;
          registerModal.value.quotationReview(quot.value);
        }
      }

      function refreshQuoteList() {
        const modalInstance = CProjectQuoteListInfoModal.value;
        if (modalInstance && typeof modalInstance.refresh === 'function') {
          modalInstance.refresh(orderInfoData.value?.csubProject?.id);
        }
      }

      function uploadContract() {
        const record = { projectId: projectId.value, subProjectId: subProjectId.value };
        ContractregisterModal.value.disableSubmit = false;
        ContractregisterModal.value.add(record);
      }

      /**
       * 刷新
       */
      function handleSuccess() {
        orderInfo();
        handleTabClick()
      }


      function quote() {
        if (isAuth('project:c_sub_project:quote')) {
          //权限判断

          if (orderInfoData.value.csubProject.status === '报价中' && orderInfoData.value.sysUser.id === orderInfoData.value.csubProject.userId) {
            quoteAdd();
          }
        }
      }

      function quotationReview() {

        if (isAuth('project:c_sub_project:quotationReview')) {
          //权限判断
          if (orderInfoData.value.csubProject.status === '审核中') {
            quoteEdit();
          }

        }
      }

      async function updateStatus(status) {
        const params = { id: subProjectId.value, status: status };
        await postUpdateStatus(params);
        handleSuccess();
      }

      /**
       * 修改状态
       */
      function updateStatue(subProjectId, newStatus) {
        const defaultValueRef = reactive<Record<string, any>>({
          subProjectId: subProjectId,
          newStatus: newStatus,
        });
        subProjectStatusLogRegisterModal.value.disableSubmit = false;
        subProjectStatusLogRegisterModal.value.add(defaultValueRef);
        orderInfo();
      }

     function handleTabClick() {
         projectQuoteRef.value?.refresh?.()
        paymentRequestRef.value?.refresh?.()
        acceptanceRef.value?.refresh?.()
         contractRef.value?.refresh?.()
        fileRef.value?.refresh?.()
      }

      return {
        orderInfo,
        subProjectStatusLogRegisterModal,
        route,
        orderInfoData,
        updateStatue,
        refreshQuoteList,
        subProjectId,
        handleSuccess,
        subProjectStatusLogs,
        currentStep,
        allSteps,
        contractorOptions,
        filterOption,
        contractorId,
        activeTabKey,
        PaymentRequestModal,
        quoteAdd,
        registerModal,
        uploadContract,
        ContractregisterModal,

        handleViewFile,
        viewFileDetail,
        quote,
        quotationReview,
        updateStatus,
        projectQuoteRef,
        paymentRequestRef,
        acceptanceRef,
        contractRef,
        fileRef,
        handleTabClick,
      };
    },
  });
</script>
<style lang="less" scoped>
  .custom-label {
    font-weight: bold;
    color: gray;
    font-size: 18px;
  }
</style>
